<template>
  <div id="Merchant">
    <!-- 查询条件 -->
    <el-form :inline="true" class="demo-form-inline" :model="searchForm">
      <el-form-item label="门店名称">
        <el-input placeholder="请输入昵称" v-model="searchForm.shopName"></el-input>
      </el-form-item>
      <el-form-item label="门店类型">
        <el-select placeholder="请选择类型" v-model="searchForm.shopType">
          <el-option label="宝妈/团长" value="1"></el-option>
          <el-option label="驿站/快递点" value="2"></el-option>
          <el-option label="超市/便利点" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-icon-search" @click="search"> 查询</el-button>
        <el-button class="el-icon-refresh" @click="onRefresh"> 重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="merchantId" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="nickName" label="申请用户" width="120" align="center"></el-table-column> <!-- 修改 prop 为 nickName -->
      <el-table-column prop="shopImg" label="门店图片" width="100" align="center">
        <template slot-scope="scope">
          <img :src="'/img'+scope.row.shopImg" alt="门店图片" style="width: 60px; height: 60px;" align="center">
        </template>
      </el-table-column>
      <el-table-column prop="shopName" label="门店名称" width="180" align="center"></el-table-column>
      <el-table-column prop="shopType" label="门店类型" width="120" align="center">
        <template slot-scope="scope">
          {{ getShopTypeText(scope.row.shopType) }}
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="申请时间" width="200" align="center"></el-table-column>
      <el-table-column label="审核状态" width="120" align="center">
        <template slot-scope="scope">
          {{ getCheckTagText(scope.row.checkTag) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="openEditDialog(scope.row)" class="el-icon-edit"> 修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" class="el-icon-delete"> 注销</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <!-- 修改模态框 -->
    <el-dialog
        title="修改商户信息"
        :visible.sync="editDialogVisible"
        width="500px"
        :before-close="handleClose">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="门店名称">
          <el-input v-model="editForm.shopName" :disabled="true"></el-input> <!-- 添加 disabled 属性 -->
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="editForm.name" :disabled="true"></el-input> <!-- 添加 disabled 属性 -->
        </el-form-item>
        <el-form-item label="身份证">
          <el-input v-model="editForm.idCard" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="门店地址">
          <el-input v-model="editForm.address" :disabled="true"></el-input> <!-- 添加 disabled 属性 -->
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="editForm.detailAddress" :disabled="true"></el-input> <!-- 添加 disabled 属性 -->
        </el-form-item>
        <el-form-item label="门店类型">
          <el-select v-model="editForm.shopType" :disabled="true">
            <el-option label="宝妈/团长" value="1"></el-option>
            <el-option label="驿站/快递点" value="2"></el-option>
            <el-option label="超市/便利点" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="editForm.checkTag">
            <el-option label="等待审核" value="S001-1"></el-option>
            <el-option label="审核未通过" value="S001-2"></el-option>
            <el-option label="审核通过" value="S001-3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
              v-model="editForm.createDate"
              type="date"
              placeholder="选择申请时间"
              :disabled="false">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker
              v-model="editForm.checkerTime"
              type="date"
              placeholder="选择审核时间"
              :disabled="false">
          </el-date-picker>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Merchant",
  data() {
    return {
      searchForm: {
        shopName: '',
        shopType: '',
        createDate: '',
        imageFileName: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      editDialogVisible: false,
      editForm: {
        merchantId: null,
        shopName: '',
        shopType: '',
        createDate: '',
        balance: null,
        name: '',
        idCard: '',
        phone: '',
        address: '',
        detailAddress: '',
        onOff: null,
        checker: '',
        checkerTime: null,
        checkReason: '',
        checkTag: '',
        status: '',
        shopImg: ''
      },
      checkTagMap: {
        "S001-1": "等待审核",
        "S001-2": "审核未通过",
        "S001-3": "审核通过"
      },
      shopTypeMap: {
        "1": "宝妈/团长",
        "2": "驿站/快递点",
        "3": "超市/便利点"
      }
    };
  },
  methods: {
    search() {
      let startDate = '';
      let endDate = '';
      if (this.searchForm.createDate && this.searchForm.createDate.length === 2) {
        startDate = this.searchForm.createDate[0];
        endDate = this.searchForm.createDate[1];

        // 验证日期格式
        const start = new Date(startDate);
        const end = new Date(endDate);
        if (isNaN(start.getTime()) || isNaN(end.getTime())) {
          this.$message.error('日期格式不正确，请重新输入');
          return;
        }

        if (start > end) {
          this.$message.error('开始日期不能大于结束日期，请重新输入');
          return;
        }
      }
      const imageFileName = this.searchForm.imageFileName;
      this.$axios.get('http://localhost:8090/merchant/page', {
        params: {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          shopName: this.searchForm.shopName,
          shopType: this.searchForm.shopType,
          startDate: startDate,
          endDate: endDate,
          imageFileName: imageFileName
        }
      }).then(response => {
        if (response.status === 200) {
          this.tableData = response.data.rows;
          this.total = response.data.total;
        } else {
          this.$message.error('查询失败，请稍后再试');
        }
      }).catch(error => {
        console.error(error);
        this.$message.error('查询失败，请检查网络连接');
      });
    },
    openEditDialog(row) {
      this.editDialogVisible = true;
      this.$set(this.editForm,'merchantId', row.merchantId);
      this.$set(this.editForm,'shopName', row.shopName);
      this.$set(this.editForm,'shopType', row.shopType);
      if (row.createDate) {
        this.$set(this.editForm, 'createDate', new Date(row.createDate));
      }
      this.$set(this.editForm, 'balance', row.balance);
      this.$set(this.editForm, 'name', row.name);
      this.$set(this.editForm, 'idCard', row.idCard);
      this.$set(this.editForm, 'phone', row.phone);
      this.$set(this.editForm, 'address', row.address);
      this.$set(this.editForm, 'detailAddress', row.detailAddress);
      this.$set(this.editForm, 'onOff', row.onOff);
      this.$set(this.editForm, 'checker', row.checker);
      if (row.checkerTime) {
        this.$set(this.editForm, 'checkerTime', new Date(row.checkerTime));
      }
      this.$set(this.editForm, 'checkReason', row.checkReason);
      this.$set(this.editForm, 'checkTag', row.checkTag);
      this.$set(this.editForm, 'status', row.status);
      this.$set(this.editForm,'shopImg', row.shopImg);
    },
    submitEdit() {
      // 转换日期格式
      if (this.editForm.createDate) {
        const options = {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        };
        this.editForm.createDate = this.editForm.createDate.toLocaleString('zh-CN', options).replace(/\//g, '-');
      }
      if (this.editForm.checkerTime) {
        const options = {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        };
        this.editForm.checkerTime = this.editForm.checkerTime.toLocaleString('zh-CN', options).replace(/\//g, '-');
      }

      this.$axios.put('http://localhost:8090/merchant/update', this.editForm).then(response => {
        if (response.data) {
          this.$message.success('修改成功');
          this.editDialogVisible = false;
          this.search();
        } else {
          this.$message.error('修改失败');
        }
      }).catch(error => {
        console.error(error);
      });
    },
    handleClose() {
      this.editDialogVisible = false;
      this.$set(this.editForm,'merchantId', null);
      this.$set(this.editForm,'shopName', '');
      this.$set(this.editForm,'shopType', '');
      this.$set(this.editForm, 'createDate', null);
      this.$set(this.editForm, 'balance', null);
      this.$set(this.editForm, 'name', '');
      this.$set(this.editForm, 'idCard', '');
      this.$set(this.editForm, 'phone', '');
      this.$set(this.editForm, 'address', '');
      this.$set(this.editForm, 'detailAddress', '');
      this.$set(this.editForm, 'onOff', null);
      this.$set(this.editForm, 'checker', '');
      this.$set(this.editForm, 'checkerTime', null);
      this.$set(this.editForm, 'checkReason', '');
      this.$set(this.editForm, 'checkTag', '');
      this.$set(this.editForm, 'status', '');
      this.$set(this.editForm,'shopImg', '');
    },
    handleDelete(index, row) {
      this.$confirm('确定要删除该商户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`http://localhost:8090/merchant/delete/${row.merchantId}`).then(response => {
          if (response.data) {
            this.$message.success('删除成功');
            this.search();
          } else {
            this.$message.error('删除失败');
          }
        }).catch(error => {
          console.error(error);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 切换每页数量后重置到第一页
      this.search();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.search();
    },
    onRefresh() {
      this.searchForm = {
        shopName: '',
        shopType: '',
        createDate: ''
      };
      this.currentPage = 1;
      this.search();
    },
    batchDelete() {
      // 由于没有勾选框，这里的批量删除逻辑需要根据实际情况调整
      // 目前代码保留，仅作提示
      this.$message.warning('此功能依赖勾选框，当前已移除勾选框，无法使用');
    },
    getCheckTagText(checkTag) {
      return this.checkTagMap[checkTag] || checkTag;
    },
    getShopTypeText(shopType) {
      return this.shopTypeMap[shopType] || shopType;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('merchantId', this.editForm.merchantId);

        this.$axios.post('http://localhost:8090/merchant/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(response => {
          if (typeof response.data === 'string') {
            this.editForm.shopImg = response.data;
            this.$message.success('图片上传成功');
          } else {
            this.$message.error('图片上传失败');
          }
        }).catch(error => {
          console.error(error);
          this.$message.error('图片上传失败');
        });
      }
    }
  },
  mounted() {
    this.search();
  }
};
</script>

<style scoped>
/* 添加一些样式以确保页面美观 */
.demo-form-inline {
  margin-bottom: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
